package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.itheima.service.OrderSettingService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.mapper.OrderSettingMapper;
import com.itheima.pojo.OrderSetting;
import com.itheima.utils.DateUtil;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@DubboService(timeout = 5000)
public class OrderSettingServiceImpl extends ServiceImpl<OrderSettingMapper, OrderSetting> implements OrderSettingService {

    @Override
    @Transactional
    public void importData(List<String[]> list) {
        //循环读取
        if (list!=null&&list.isEmpty()==false){
            List<OrderSetting> orderSettings=new ArrayList<>();
            list.stream().forEach(row->{
                String orderDate=row[0];
                Integer num = Integer.valueOf(row[1]);
                //根据日期查询预约设置数据
                OrderSetting orderSetting=findByDate(orderDate);
                //如果不存在就新建数据
                if (orderSetting==null){
                    orderSetting=new OrderSetting();
                }
                orderSetting.setNumber(num);
                //将字符串格式数据转化为日期对象
                orderSetting.setOrderDate(DateUtil.parseDate(orderDate));
                orderSettings.add(orderSetting);
            });
            this.saveOrUpdateBatch(orderSettings);
        }
    }

    @Override
    public OrderSetting findByDate(String orderDate) {
        //QueryWrapper
        QueryWrapper<OrderSetting> queryWrapper = new QueryWrapper<>();
        // where order_date = '2021-03-19'
        queryWrapper.lambda().eq(OrderSetting::getOrderDate,orderDate);

        return this.getOne(queryWrapper);
    }

    /**
     * 根据月份查询预约情况日期
     * */
    @Override
    public Map findByYearMonth(String yearMonth) {

        //模糊查询
        QueryWrapper<OrderSetting> queryWrapper=new QueryWrapper<>();
        queryWrapper.lambda().likeRight(OrderSetting::getOrderDate,yearMonth);

        List<OrderSetting> list = this.list(queryWrapper);
        Map map=new HashMap<>();
        list.stream().forEach(OrderSetting->{
            map.put(DateUtil.formatDate(OrderSetting.getOrderDate()),OrderSetting);
        });

        return map;
    }

    @Override
    public Boolean updateOrderSetting(String orderDate, Integer num) {
        //先查询
        OrderSetting orderSetting = this.findByDate(orderDate);
        //在判断
        if (orderSetting==null){
            orderSetting = new OrderSetting();
        }
        orderSetting.setNumber(num);
        orderSetting.setOrderDate(DateUtil.parseDate(orderDate));

        return this.saveOrUpdate(orderSetting);
    }

    @Override
    public Boolean clearOssData() {
        return baseMapper.clearOssData();
    }


}